﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JGSY.SerialCommunication.UpperComputer.Core
{
    public sealed class ModbusLrcCalculator
    {
        public static byte Calculate(byte[] data)
        {
            if (data == null || data.Length == 0)
                throw new ArgumentNullException(nameof(data));

            byte lrc = 0;
            foreach (byte b in data)
            {
                lrc = (byte)((lrc + b) & 0xFF);
            }
            lrc = (byte)(((lrc ^ 0xFF) + 1) & 0xFF); // 取反加1
            return lrc;
        }

        public static bool Verify(byte[] data, byte expectedLrc)
        {
            if (data == null || data.Length < 1)
                return false;

            byte calculatedLrc = Calculate(data);
            return calculatedLrc == expectedLrc;
        }
         
    }
}
